package shooter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;


class Server implements Runnable {
	ServerSocket ss;
	Socket sc1;
	Socket sc2;
        
	public Server(ServerSocket ss) {
		this.ss = ss;
		new Thread(this).start();
	}
	/**
	 * @param args
	 */
        int port=3001;
	public static void main(String[] args) throws IOException {
            int port=3001;
            if (args.length > 0) {
                try {
                    port = Integer.parseInt(args[0]);
                } catch (NumberFormatException e) {
                    System.err.println("Lisav22rtuseks sobib ainult port!");
                    System.exit(1);
                }
            }
            if(args.length>0){port=Integer.parseInt(args[0]);}
        new Server(new ServerSocket(port));
        System.out.print("-------------TLY Shooter 2D GAME server----------------\n");
        System.out.print("Server on k2ivitunud. Port:"+ port);
	}

	@Override
	public void run() {
		try {

			while (true) {
				sc1 = ss.accept();
				sc2 = ss.accept();
				sc1.setSoTimeout(500);
				sc2.setSoTimeout(500);
				InputStream is1 = sc1.getInputStream();
				InputStream is2 = sc2.getInputStream();
				OutputStream os1 = sc1.getOutputStream();
				OutputStream os2 = sc2.getOutputStream();
				// os1.write(is2.read());
				boolean k6ne = true;
				while (k6ne) {
					try {
						int bait = is2.read();
						while (bait != -1) {
							os1.write(bait);
							bait = is2.read();
						}
						k6ne=false;
					} catch (SocketTimeoutException se) {
						System.out.println("Infovahetus esimesele");
					}
					try {
					  if(k6ne){
						int bait = is1.read();
						while (bait != -1) {
							os2.write(bait);
							bait = is1.read();
						}
						k6ne=false;
					  }
					} catch (SocketTimeoutException se) {
						System.out.println("Infovahetus teisele");
					}
				}
			}
		} catch (IOException ex) {
			// throw new RuntimeException(ex);
			System.out.println(ex);
		}
	}

}